<template>
  <view class="container">
    <view class="logo" @dblclick="handleAccount">小鹏打车，一路畅行</view>
    <view class="login">
      <input placeholder="请输入手机号" type="number" maxlength="11" v-model="phone" class="login--input" />
      <view class="login--code">
        <input placeholder="验证码" type="number" maxlength="6" class="login--input" v-model="code" />
        <text @click="handleGetVerifyCode" :class="['login--send-btn', { 'login--send-btn__disabled': isDisableCode }]">{{
          codeText }}</text>
      </view>
    </view>
    <button class="login--btn" @click="handleLogin">登录</button>
  </view>

  <view class="modal-mask" v-if="showModal" @tap="closeModal">
    <view class="modal-container" @tap.stop>
      <view class="modal-header">
        <text class="modal-title">用户不存在，是否注册</text>
        <text class="modal-close" @tap="closeModal">×</text>
      </view>
      <view class="modal-content">
        <text>手机号 {{ phone }} 未注册，是否立即注册？</text>
      </view>
      <view class="modal-footer">
        <button class="modal-btn modal-btn-cancel" @tap="closeModal">取消</button>
        <button class="modal-btn modal-btn-confirm" @tap="confirmRegister">确定</button>
      </view>
    </view>
  </view>
</template>
<script setup>
import { _IsPhone } from '@gykeji/jsutil';
import { computed, onMounted, ref } from 'vue';
import { ApiGetVerifyCode, ApiPostVerifyCodeCheck } from '../api/user'
import { HandleApiError, ShowToast } from '../utils';
import { useStore } from 'vuex';
import { onLoad } from '@dcloudio/uni-app';
//定位
import { locationService } from '@/utils/location.js';
//sse
import { useSseService } from '@/service/sseService-web.js';
//jwt解码
import { decodeToken } from '@/utils/decodeToken.js';

const { eventData, error, isConnected, connectSSE, reconnectSSE, closeSSE } = useSseService();

//实时定位经纬度
const realTimeLocation = ref({
  longitude: null,
  latitude: null,
  // address: null
});
//实时定位是否开启
const isRealTimeLocating = ref(false);

const $store = useStore();
const token = computed(() => $store.state.token);
const showModal = ref(false);
let codeText = ref('获取验证码');
let codeTimerNum = ref(0);
let codeTimer = null;
let isDisableCode = computed(() => codeTimerNum.value !== 0);
let phone = ref('');
let code = ref('');
defineExpose({
  phone
});
onMounted(() => {
  console.log("登录页面挂载");
  if (token.value) {
    uni.redirectTo({ url: '/pages/index/index' });
  }
  //   if(token.value){
  // //解码token
  // const decodedToken = decodeToken(token.value);
  // console.log("解码token：",decodedToken);

  // if (!decodedToken) {
  //     console.error('无法从token中获取用户ID');
  // 	return;
  // }else{
  // 	// console.log("token中解码获取用户ID：",decodedToken?.phone,";身份：",decodedToken?.identity);
  // 	connectSSE(decodedToken.phone, decodedToken.identity);
  // 	uni.redirectTo({url:'/pages/index/index'});
  // }
  //   }
})
const handleGetVerifyCode = async () => {
  if (isDisableCode.value || !verifyPhone(phone.value)) {
    return false;
  }
  codeTimerNum.value = 60;
  calcTimer();
  const { error, result } = await ApiGetVerifyCode({ passengerPhone: phone.value });
  console.log(result);
  alert(result)
  console.log(result.data);
  console.log(error, { passengerPhone: phone.value })
}

const handleLogin = async () => {
  // if(!verifyPhone(phone.value)){
  //     return false;
  // }
  // if(!code.value){
  //     ShowToast('请输入验证码');
  //     return false;
  // }

  const { error, result } = await ApiPostVerifyCodeCheck({
    passengerPhone: phone.value,
    verificationCode: code.value
  }, {
    header: {
      notVerifyToken: true
    }
  });
  console.log(result);


  if (result == 999) {
    console.log('999，弹窗应该弹出');
    showModal.value = true;
  } else if (result == 1099) {
    // ElMessage.warning("验证码错误");
    ShowToast('验证码错误');
  } else if (result == 5656) {
    // ElMessage.warning("你输入太频繁啦,一分钟后再来吧");
    ShowToast('你输入太频繁啦,一分钟后再来吧');
  }
  else {
    console.log(result);
    console.log(result.accessToken);
    const token = result.accessToken;
    $store.commit('setToken', result.accessToken);

    uni.redirectTo({ url: '/pages/index/index' });
    //开启定位，连接sse
    // toRealTimeLocation();
    //sse连接
    // const decodedToken = decodeToken(result.accessToken);
    // console.log("解码token：", decodedToken);

    // if (!decodedToken) {
    //   console.error('无法从token中获取用户ID');
    //   return;
    // } else {
    //   // console.log("token中解码获取用户ID：",decodedToken?.phone,";身份：",decodedToken?.identity);
    //   connectSSE(decodedToken.phone, decodedToken.identity);
    // }
  }
}

const confirmRegister = () => {
  uni.navigateTo({ url: `/pages/registerPage?phone=${encodeURIComponent(phone.value)}` });
  showModal.value = false;
}

const closeModal = () => {
  showModal.value = false;
}

// 新增注册处理方法

const calcTimer = () => {
  codeTimerNum.value--;
  if (codeTimerNum.value === 0) {
    clearTimeout(codeTimer);
    codeText.value = '获取验证码';
    return false;
  };
  codeText.value = `${codeTimerNum.value}s后重新获取`;
  setTimeout(() => {
    calcTimer();
  }, 1000)
}
const verifyPhone = (phone) => {
  let result = phone && _IsPhone(phone);
  if (!result) {
    ShowToast('请填写正确手机号！');
    result = false;
  }
  return result;
}

const handleAccount = () => {
  uni.navigateTo({ url: '/pages/account' })
}
// const clear = () =>{
//     uni.clearStorageSync();
// }

//请求定位权限，开启实时定位
const toRealTimeLocation = async () => {
  if (isRealTimeLocating.value) {
    locationService.stopRealTimeLocation();
    isRealTimeLocating.value = false;
  } else {
    try {
      // 注册位置变化回调
      locationService.onLocationChange((location) => {
        realTimeLocation.value = location;
      });

      await locationService.startRealTimeLocation();
      isRealTimeLocating.value = true;
      uni.showToast({
        title: '已开启实时定位',
        icon: 'success'
      });
    } catch (error) {
      uni.showToast({
        title: '开启实时定位失败',
        icon: 'none'
      });
      console.error('开启实时定位失败:', error);
    }
  }
};
</script>

<style lang="scss" scoped>
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.modal-container {
  width: 80%;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
}

.modal-header {
  padding: 20px;
  position: relative;
  border-bottom: 1px solid #eee;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
}

.modal-close {
  position: absolute;
  right: 20px;
  top: 20px;
  font-size: 24px;
  color: #999;
}

.modal-content {
  padding: 20px;
  font-size: 16px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  padding: 15px;
  border-top: 1px solid #eee;
}

.modal-btn {
  margin-left: 15px;
  padding: 8px 15px;
  border-radius: 4px;
  font-size: 14px;
}

.modal-btn-cancel {
  background-color: #f5f5f5;
  color: #333;
}

.modal-btn-confirm {
  background-color: #007aff;
  color: #fff;
}

.logo {
  font-size: 46rpx;
  text-align: center;
  margin: 100rpx 0 84rpx 0;
  font-weight: bold;
}

.login {
  width: 650rpx;
  margin: 0 auto;

  &--input {
    border-bottom: 2rpx solid $uni-border-color;
    width: 650rpx;
    height: 100rpx;
    font-size: $uni-font-size-lg;
  }

  &--code {
    position: relative;
  }

  &--send-btn {
    position: absolute;
    right: 0;
    z-index: 999;
    top: 36rpx;
    color: $uni-color-primary;

    &__disabled {
      color: $uni-text-color-disable;
    }
  }

  &--btn {
    width: 650rpx;
    font-size: $uni-font-size-lg;
    margin: 60rpx 50rpx 40rpx;
    background: $uni-color-primary;
    color: $uni-text-color-inverse;
  }
}
</style>